package fdoj.eventInvitations.servlet;

import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.persistence.EntityManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import fdoj.eventInvitations.dao.EventDao;
import fdoj.eventInvitations.dao.PersonDao;
import fdoj.eventInvitations.entity.Contact;
import fdoj.eventInvitations.entity.Event;
import fdoj.eventInvitations.entity.Person;

public class AddContactController extends HttpServlet {
	@EJB
	private PersonDao personDao;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			HttpSession session = request.getSession(true);
			Person person = (Person) request.getSession().getAttribute("loggedUser");
			if (person == null) {
				response.sendRedirect(response.encodeRedirectURL("./index"));
				return;
			}
			if (person != null) {
				String firstName = request.getParameter("firstName");
				String lastName = request.getParameter("lastName");
				String email = request.getParameter("email");

				Contact contact = new Contact();
				contact.setEmail(email);
				contact.setFirstName(firstName);
				contact.setLastName(lastName);
				contact.setValid(true);
				person.addContact(contact);
				personDao.merge(person);
				person=personDao.findById(person.getId());
				session.setAttribute("loggedUser", person);
				response.sendRedirect(response
						.encodeRedirectURL("./addressbook"));
				return;
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		response.sendRedirect(response.encodeRedirectURL("./index"));

	}

}
